package com.tacademy.jmtwitter;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;

import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.client.ClientProtocolException;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.*;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class JMTwitterActivity extends TabActivity implements
		OnItemClickListener {
	public int flag_tap_userTimeline;
	public int flag_tap_homeTimeline;
	public final int WRITE = 1;
	public final int REPLY = 2;
	public final int SETFRIEND = 3;
	int mCountNew, mListClickPosition;
	static long sinceId, maxId;
	Handler mHandler = new Handler();
	public int mStat = 0;
	ArrayList<Status> mDataList, mPublicDataList;
	ProgressBar mPBar;
	ListView mList;
	TimelineAdapter mAdapter;
	FrameLayout mFrame;
	TextView mName;
	String mStr1, mStr2, mStr3;
	EditText mEdit;
	Intent mIntent;
	TabHost mTab;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mIntent = getIntent();
		mStr1 = mIntent.getStringExtra(Authorize.EXTRA1_STRING);
		mStr2 = mIntent.getStringExtra(Authorize.EXTRA2_STRING);
		mStr3 = mIntent.getStringExtra(Authorize.EXTRA3_STRING);
		Log.d("jmkkk", "넘어옴" + mStr1);
		Log.d("jmkkk", "넘어옴" + mStr2);
		Log.d("jmkkk", mStr3);
		setContentView(R.layout.tab_main);
		mPBar = (ProgressBar) findViewById(R.id.progressbar);
		mFrame = (FrameLayout) findViewById(android.R.id.tabcontent);
		mName = (TextView) findViewById(R.id.textName);
		mTab = getTabHost();// 탭 호스트 객체 생성 안에 FrameLayout 배치
		TabHost.TabSpec spec;
		Drawable icon;// 리소스 아이디 알아내기위한 객체
		mName.setText(mStr3);

		spec = mTab.newTabSpec("TAB1");
		icon = getResources().getDrawable(R.drawable.ic_menu_find);
		spec.setIndicator("friendly", icon);
		Intent intent2 = new Intent(this, SearchFriendActivity.class);
		spec.setContent(intent2);
		mTab.addTab(spec);

		spec = mTab.newTabSpec("TAB2");
		icon = getResources().getDrawable(R.drawable.ic_menu_allfriends);
		spec.setIndicator("List", icon);
		spec.setContent(R.id.tab1);
		mTab.addTab(spec);

		mList = (ListView) findViewById(R.id.listView1);

		mPBar.setVisibility(View.VISIBLE);
		Log.d("jmkkk", "oncreate");

		// mAdapter = new TimelineAdapter(this, mDataList);
		Log.d("jmkkk", "parse완료");
		// mList.setAdapter(mAdapter);
		ArrayList<Status> dummyDataList;
		dummyDataList = new ArrayList<Status>();
		dummyDataList.add(new Status("", "", new User("", "", "")));
		TimelineAdapter adapter = new TimelineAdapter(JMTwitterActivity.this,
				dummyDataList);
		mList.setAdapter(adapter);
		Log.d("jmkkk", "adapter");

		mList.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Log.d("jmkkk", "wirte");
		mListClickPosition = position;
		showDialog(REPLY);

	}

	// ////////////////////////////////////메뉴부분/////////////////////////////////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.setFriend:
			showDialog(SETFRIEND);
			break;
		case R.id.menuLogOut:
			SharedPreferences pref = getSharedPreferences(Authorize.SAVE,
					MODE_PRIVATE);
			SharedPreferences.Editor edit = pref.edit();
			edit.remove(Authorize.SECRET);
			edit.remove(Authorize.TOKEN);
			edit.commit();
			cancle();
			// mIntent = new Intent();
			// mIntent.putExtra(Authorize.EXTRA4_STRING, "LogOut");
			// setResult(RESULT_OK, mIntent);
			finish();
			Log.d("jmkkk", "로그아웃");
			break;
		}
		return true;
	}

	// /////////////////////////////////////////////////////////////////////////////////

	@Override
	protected void onStart() {
		cancle();
		super.onStart();
		Log.d("jmkkk", "onStart");
		getText();

	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d("jmkkk", "onResume");
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.cancel(NotificationService.ID_NOTI);

	}
	@Override
	protected void onPause() {
		super.onPause();
		
	}
	@Override
	protected void onStop() {
		super.onStop();
		Log.d("jmkkk", "onStop");
/////////////sinceId  count 위해 저장
		SharedPreferences pref = getSharedPreferences(Authorize.SAVE, MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		edit.putLong("sinceId", sinceId);
		edit.commit();
		Log.d("jmkkk", "아이디 저장!!");
		schedule(JMTwitterActivity.this, NotificationService.class);
		Log.d("jmkkk", "스케쥴시작");
	}

	public void onClick(View v) {
		switch (mTab.getCurrentTab()) {
		case 0:
			Toast.makeText(JMTwitterActivity.this, "이탭은 안됩니다!!!", Toast.LENGTH_LONG)
			.show();
			break;
		case 1:
			switch (v.getId()) {
			case R.id.maxId:
				maxId();
				Toast.makeText(JMTwitterActivity.this, "기다리세요", Toast.LENGTH_LONG)
						.show();
				mPBar = (ProgressBar) findViewById(R.id.progressbar);
				mPBar.setVisibility(View.VISIBLE);
				mPBar.setFocusable(true);
				Log.d("jmkkk", "maxId");
				break;

			case R.id.sinceId:
				sinceId();
				Toast.makeText(JMTwitterActivity.this, "기다리세요", Toast.LENGTH_LONG)
						.show();
				mPBar.setVisibility(View.VISIBLE);
				mPBar.setFocusable(true);
				Log.d("jmkkk", "sinceId");
				break;
			case R.id.wirte:
				Log.d("jmkkk", "wirte");
				showDialog(WRITE);
				// Intent intent = new
				// Intent(JMTwitterActivity.this,NotificationService.class);
				// startService(intent);
				// Log.d("jmkkk", "StartService");
				break;

			default:
				break;
			}
			break;
		default:
			break;
		}
		
	}

	public void getText() {
		new Thread() {
			@Override
			public void run() {
				Log.d("jmkkk", "getTextRun");
				mDataList = new TwitterApi(mStr1, mStr2).getHomeTimeline(5, 0,
						0);
				getSinceId();
				getMaxId();
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						mPBar = (ProgressBar) findViewById(R.id.progressbar);
						mPBar.setVisibility(View.INVISIBLE);
						Toast.makeText(JMTwitterActivity.this, "가져와쪄염~",
								Toast.LENGTH_LONG).show();
						mAdapter = new TimelineAdapter(JMTwitterActivity.this,
								mDataList);
						mList.setAdapter(mAdapter);
						mAdapter.notifyDataSetChanged();

					}
				});

			}
		}.start();
	}

	public void sinceId() {
		new Thread() {
			@Override
			public void run() {
				Log.d("jmkkk", "run");
				ArrayList<Status> dataList = new ArrayList<Status>();
				dataList = new TwitterApi(mStr1, mStr2).getHomeTimeline(5,
						sinceId, 0);
				dataList.addAll(mDataList);
				mDataList = dataList;
				getSinceId();
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						mPBar = (ProgressBar) findViewById(R.id.progressbar);
						mPBar.setVisibility(View.INVISIBLE);
						Toast.makeText(JMTwitterActivity.this, "가져와쪄염~",
								Toast.LENGTH_LONG).show();
						mAdapter = new TimelineAdapter(JMTwitterActivity.this,
								mDataList);
						mList.setAdapter(mAdapter);
						mAdapter.notifyDataSetChanged();
					}
				});

			}
		}.start();
	}

	public int maxId() {

		new Thread() {
			@Override
			public void run() {
				Log.d("jmkkk", "run");
				ArrayList<Status> dataList = new ArrayList<Status>();
				dataList = new TwitterApi(mStr1, mStr2).getHomeTimeline(6, 0,
						maxId);
				mCountNew = dataList.size();
				mDataList.remove(mDataList.size() - 1);
				mDataList.addAll(dataList);
				getMaxId();
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						mPBar = (ProgressBar) findViewById(R.id.progressbar);
						mPBar.setVisibility(View.INVISIBLE);
						Toast.makeText(JMTwitterActivity.this, "가져와쪄염~",
								Toast.LENGTH_LONG).show();
						mAdapter = new TimelineAdapter(JMTwitterActivity.this,
								mDataList);
						mList.setAdapter(mAdapter);
						mAdapter.notifyDataSetChanged();
					}
				});

			}
		}.start();
		return mCountNew;
	}

	public void reTweet(final long id) {
		new Thread() {
			public void run() {
				Log.d("jmkkk", "run");
				try {
					Status stat = new TwitterApi(mStr1, mStr2).reTweet(id);
					sinceId();
				} catch (OAuthMessageSignerException e) {
					e.printStackTrace();
				} catch (OAuthExpectationFailedException e) {
					e.printStackTrace();
				} catch (OAuthCommunicationException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						mPBar = (ProgressBar) findViewById(R.id.progressbar);
						mPBar.setVisibility(View.INVISIBLE);
						Toast.makeText(JMTwitterActivity.this,
								"리트윗해쓰요~~잠시 기다리세요!!!!", Toast.LENGTH_LONG).show();

					}
				});

			}
		}.start();
	}

	public void statusUpdate(final String taxt, final long id) {
		new Thread() {
			@Override
			public void run() {
				Log.d("jmkkk", "run");
				try {
					Status stat = new TwitterApi(mStr1, mStr2).statusUpdate(
							taxt, id);
					sinceId();
				} catch (OAuthMessageSignerException e) {
					e.printStackTrace();
				} catch (OAuthExpectationFailedException e) {
					e.printStackTrace();
				} catch (OAuthCommunicationException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						mPBar = (ProgressBar) findViewById(R.id.progressbar);
						mPBar.setVisibility(View.INVISIBLE);
						Toast.makeText(JMTwitterActivity.this,
								"다보내쓰요~잠시 기다리세요!!!!", Toast.LENGTH_LONG).show();

					}
				});

			}
		}.start();
	}

	public void getSinceId() {
		sinceId = Long.parseLong(mDataList.get(0).getId());
		Log.d("jmkkk", "sinceId = " + sinceId);
		// return sinceId;

	}

	public long getMaxId() {
		maxId = Long.parseLong(mDataList.get(mDataList.size() - 1).getId());
		Log.d("jmkkk", "maxId = " + maxId + "count = " + mDataList.size());
		return maxId;
	}

	@Override
	protected void onRestoreInstanceState(Bundle state) {
		super.onRestoreInstanceState(state);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case WRITE:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Tweet");
			mEdit = new EditText(this);
			builder.setView(mEdit);
			builder.setPositiveButton("WRITE",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							statusUpdate(mEdit.getText().toString(), 0);
							mEdit.setText("");
						}
					});
			Dialog d = builder.create();
			d.setCanceledOnTouchOutside(true);
			return d;

		case REPLY:
			AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
			builder1.setTitle("Mention");
			mEdit = new EditText(this);
			builder1.setView(mEdit);
			builder1.setPositiveButton("REPLY",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							statusUpdate("@"
									+ mDataList.get(mListClickPosition).getUser()
									.getScreen_name()+" "+
									mEdit.getText().toString(),
									Long.parseLong(mDataList.get(
											mListClickPosition).getId()));
							mEdit.setText("");
						}
					});
			builder1.setNegativeButton("Retweet",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							reTweet(Long.parseLong(mDataList.get(
									mListClickPosition).getId()));
							
						}
					});

			Dialog d1 = builder1.create();
			d1.setCanceledOnTouchOutside(true);
			return d1;
		case SETFRIEND:
			AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
			builder2.setTitle("변경");
			builder2.setMessage(SearchFriendActivity.mScreenName);
			mEdit = new EditText(this);
			builder2.setView(mEdit);
			builder2.setNegativeButton("Retweet",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if("".equals(mEdit.getText().toString())){
								Toast.makeText(JMTwitterActivity.this, "잘못입력되었습니다.", Toast.LENGTH_SHORT).show();
							}else{
								SearchFriendActivity.mScreenName = mEdit.getText().toString();
								Toast.makeText(JMTwitterActivity.this, SearchFriendActivity.mScreenName+" 으로 변경!", Toast.LENGTH_SHORT).show();
							}
						}
					});

			Dialog d2 = builder2.create();
			d2.setCanceledOnTouchOutside(true);
		default:
			break;
		}

		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case REPLY:
			dialog.setTitle("@"
					+ mDataList.get(mListClickPosition).getUser()
					.getScreen_name());
			
			break;

		default:
			break;
		}
		super.onPrepareDialog(id, dialog);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
			
		super.onSaveInstanceState(outState);
	}

	public void schedule(Context packageContext, Class<?> cls) {
		Log.d("jmkkk", "알람 시작");
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent intent = new Intent(packageContext, cls);
		PendingIntent operation = PendingIntent.getService(this, 0, intent, 0);
		am.setRepeating(AlarmManager.RTC_WAKEUP,
				System.currentTimeMillis() + 1000, // 최초시간
				10000, // 반복시간
				operation);
	}

	public void cancle() {
		Log.d("jmkkk", "알람 캔슬");
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent intent = new Intent(JMTwitterActivity.this, NotificationService.class);
		PendingIntent operation = PendingIntent.getService(this, 0, intent, 0);
		am.cancel(operation);

	}
	class AdvancedThread extends AsyncTask<URL, Integer, Long>{
		
		@Override
		protected void onPreExecute() {
			// TODO 플래그값 지정해서 넣자 탭 & 버튼 조합
			super.onPreExecute();
		}
		
		@Override
		protected Long doInBackground(URL... params) {
			// TODO Auto-generated method stub
			return null;
		}
		
		@Override
		protected void onPostExecute(Long result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}

}